import os
import sys
import time
import json
import django
import uuid

BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
print(os.path.abspath(__file__))
print(BASE_DIR)
sys.path.extend([BASE_DIR, ])
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "finance_c2c.settings")
django.setup()
from core.wchat.mini_base import wechat_client, wechat_client_howhow
from core.tools.oss_upload import oss_upload_file
from finance_c2c.local_settings import SECRET_KEY
from core.tools.encryption import hashlib_md5
from core.wchat.wx_base import mc

from django.contrib.auth import get_user_model
from apps.coffee.models import Channel

UserModel = get_user_model()

# 目前只用的这个脚本来生成券
# 先注册渠道和用户
# 然后再从后台批量生存券到此渠道下面

class PoolChannelError(Exception):
    """ Base class for lookup errors. """

    def __init__(self, *args, **kwargs):  # real signature unknown
        pass

    @staticmethod  # known case of __new__
    def __new__(*args, **kwargs):  # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass


def create_user(mobile, channel=None):
    if not channel:
        channel = Channel.objects.get(key=channel)
    UserModel.objects.get_or_create(
        mobile=mobile,
        username=mobile,
        can_transfer=False,
        coffee_channel=channel,
        is_coffee_manager=True,
        coffee_new_user=False,
        can_share_coupon=False
    )


def add_channel(channel_key, name, pool_status=False):
    channel = Channel.objects.filter(key=channel_key)
    if channel.exists():
        if pool_status:
            return channel.first()
        raise KeyError("该渠道已存在")
    else:
        instance = Channel.objects.create(
            name=name,
            key=channel_key,
            secret=uuid.uuid4().hex
        )
        return instance


# 用户生成领取码(******重要******) 有用的
# 静态码 和 用户码成了 一个逻辑
# 先生成用户
def make_mini_code(page="pages/ling/ling", channel_key="zhongxinyinhang", active_key=None, pool_key=None, quota="13", c_type=2):
    """

    :param page:
    :param channel_key:
    :param active_key: 相同活动不能领取多次
    :param pool_key: 公用一个渠道池子
    :return:
    """
    request_time = int(time.time() * 1000)
    p = str(request_time) + SECRET_KEY
    # print(p)
    sign = hashlib_md5(p)
    data = {"sign": sign, "request_time": request_time, "channel_key": channel_key,
            "give_record_list": [{"c_type": c_type, "num": "1", "quota": quota}]}
    # data = {"sign": sign, "request_time": request_time, "channel_key": channel_key,
    #         "give_record_list": [{"c_type": "6", "num": "1", "quota": "0"}]}
    if active_key:
        data["active_key"] = active_key
    if pool_key:
        data["pool_key"] = pool_key
    params = json.dumps(data)
    # print(data, "sss")
    key = uuid.uuid1().hex
    response = wechat_client.wxa.get_wxa_code_unlimited(key, page=page)
    mc.set(key, params)
    # print(key)
    url = oss_upload_file(response.content)
    if pool_key:
        print(f"池子key:{pool_key}    {channel_key}       {url}")
    else:
        print(f"{channel_key}       {url}")
    return url


# 最后小程序用的这个  *********这个是正常使用这的**************
def make_mini_code_howho(page="pages/ling/ling", channel_key="zhongxinyinhang", active_key=None, pool_key=None, quota="13", c_type=2):
    """

    :param page:
    :param channel_key:
    :param active_key: 相同活动不能领取多次
    :param pool_key: 公用一个渠道池子
    :return:
    """
    request_time = int(time.time() * 1000)
    p = str(request_time) + SECRET_KEY
    # print(p)
    sign = hashlib_md5(p)
    data = {"sign": sign, "request_time": request_time, "channel_key": channel_key,
            "give_record_list": [{"c_type": c_type, "num": "1", "quota": quota}]}
    # data = {"sign": sign, "request_time": request_time, "channel_key": channel_key,
    #         "give_record_list": [{"c_type": "6", "num": "1", "quota": "0"}]}
    if active_key:
        data["active_key"] = active_key
    if pool_key:
        data["pool_key"] = pool_key
    params = json.dumps(data)
    # print(data, "sss")
    key = uuid.uuid1().hex
    response = wechat_client_howhow.wxa.get_wxa_code_unlimited(key, page=page)
    mc.set(key, params)
    # print(key)
    url = oss_upload_file(response.content)
    if pool_key:
        print(f"池子key:{pool_key}    {channel_key}       {url}")
    else:
        print(f"{channel_key}       {url}")
    return url


def main():
    channel_key_list = [
        {"key": 'zzsx1', "name": "立减券"},
        # {"key": 'test_shop2', "name": "测试商家2"},
    ]
    # pool_key = "testchiziqudao"
    pool_key = False
    if pool_key:
        pool_name = "test池子渠道"
        channel_instance = add_channel(pool_key, pool_name, pool_status=True)
        create_user(pool_key, channel_instance)

    for i in channel_key_list:
        key = i.get("key")
        name = i.get("name")
        # channel_instance = add_channel(key, name)
        # create_user(key, channel_instance)
        # make_mini_code(channel_key=i, active_key="YiFreeB")  # 活动key
        if pool_key:
            make_mini_code_howho(channel_key=key, pool_key=pool_key)
        else:
            make_mini_code_howho(channel_key=key)


if __name__ == '__main__':
    # main()
    # make_mini_code_howho(channel_key="jiugerishao", quota="13")  不用了

    create_user("18601193719", "")
